package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 今日佳人
     * 给登录用户推荐最高分数的佳人
     *
     * @param loginUserId
     * @return
     */
    @Override
    public RecommendUser queryWithMaxScore(Long loginUserId) {
        Query query = new Query();
        //1. 构建查询的条件toUserId=loginUserId
        query.addCriteria(Criteria.where("userId").is(loginUserId));
        //2. 缘分值最高，按分数降序，
        query.with(Sort.by(Sort.Order.desc("score")));
        //3. 取第一个
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        return recommendUser;
    }

    /**
     * 分页查询推荐用户列表数据
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findPage(Long userId, Long page, Long pagesize) {
        //定义返回PageResult<RecommendUser>
        PageResult<RecommendUser> pageResult = new PageResult<>();
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        //1查询总记录数
        long counts = mongoTemplate.count(query, RecommendUser.class);
        long start = (page-1)*pagesize;

        //2查询当前页面需要展示的数据
        if(counts > start){ //20 > 27
            //构造分页limit 0,3
            query.limit(pagesize.intValue());//每页查询几条
            query.skip(start);//跳过1条数据
            //query.with(PageRequest.of(page,pageSize));
            query.with(Sort.by(Sort.Direction.DESC,"userId"));
            pageResult.setItems(mongoTemplate.find(query, RecommendUser.class));
        }

        long pages = counts%pagesize > 0 ? counts/pagesize+1 : counts/pagesize;
        pageResult.setCounts(counts);//总记录数
        pageResult.setPagesize(pagesize);//当前页面条数
        pageResult.setPages(pages);//总页码
        pageResult.setPage(page);
        return pageResult;
    }

    /**
     * 根据当前登录的id 和 推荐的id 查询用户推荐表
     * @param userId
     * @param loginUserId
     * @return
     */
    @Override
    public RecommendUser findByUserId(Long userId, Long loginUserId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId).and("toUserId").is(loginUserId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        return recommendUser;
    }

    /**
     * 调用服务随机获取 10个推荐用户数据
     * @param userId
     * @param count
     * @return
     */
    @Override
    public List<RecommendUser> findCards(Long userId, int count) {
        Query query = new Query();
        // 先查询user_like，取所有的likeUserId, 用户已经选过了
        query.addCriteria(Criteria.where("userId").is(userId));
        List<UserLike> likeUserList = mongoTemplate.find(query, UserLike.class);

        //取所有的likeUserId
        List<Long> likeUserIds = new ArrayList<>();
        if(!CollectionUtils.isEmpty(likeUserList)){
            for (UserLike userLike : likeUserList) {
                likeUserIds.add(userLike.getUserId());
            }
        }

        //2. 构建查询推荐表条件(toUserId=userId, userId Not in (likeUserId...)),
        // 既有随机，也有条件
        Criteria toUserId = Criteria.where("toUserId").is(userId).and("userId").nin(likeUserIds);

        //3. 查询时使用随机取样, mongodb的聚合统计
        TypedAggregation<RecommendUser> recommendUserTypedAggregation =
                TypedAggregation.newAggregation(RecommendUser.class, Aggregation.match(toUserId),
                        Aggregation.sample(count));

        // p1: 统计参数， p2: 返回 值的类型
        AggregationResults<RecommendUser> recommendUsers =
                mongoTemplate.aggregate(recommendUserTypedAggregation, RecommendUser.class);
        return recommendUsers.getMappedResults();
    }
}
